<template>
  <div class="read">
    <div id="statusBar"></div>
    <div class="nav-bar" v-if="isBar">
      <van-nav-bar :class="isLight ? 'light-read' : 'dark-read'" :title="title" left-arrow @click-left="returnBookDetails" />
    </div>

    <div class="box" @click="isControl = !isControl" v-if="operation == 0">
      <!-- 滚动阅读 -->
      <ul :style="`font-size: ${fontSize}px`" class="content" :class="isLight ? 'light-read' : 'dark-read'" v-if="contentData.length > 0">
        <li v-for="(item, index) in contentData" :key="index">{{item}}</li>
        <div>-----------------下一章请手动切换-----------------</div>
      </ul>
    </div>
    
    <!-- 翻页阅读 -->
    <van-swipe ref="swipe" class="my-swipe" :show-indicators="false" :loop="false" :class="isControl ? 'isControl' : ''" v-else>
      <van-swipe-item :style="`font-size: ${fontSize}px`" class="swipe-item" :class="isLight ? 'light-read' : 'dark-read'" v-for="(item, index) in contentDataTurn" :key="index" @click="isControl = !isControl">
        <div v-for="(item2, index2) in item" :key="index2">{{item2}}</div>
      </van-swipe-item>
      <div>-----------------下一章请手动切换-----------------</div>
    </van-swipe>

    <div class="control" v-if="isControl" :class="isLight ? 'light-read light' : 'dark-read dark'">
      <div class="top">
        <div class="setFontSize narrow" @click="toggleFontSize('narrow')"><van-icon name="minus" /></div>
        <div class="setFontSize showCurrent">{{fontSize}}</div>
        <div class="setFontSize enlarge" @click="toggleFontSize('enlarge')"><van-icon name="plus" /></div>
        <div class="operation">
          <div :class="operation == index ? 'active' : ''" v-for="(item, index) in operationData" :key="index" @click="operation = index">{{item}}</div>
        </div>
      </div>
      <div class="bottom light-control" v-if="isLight">
        <div class="control-item" @click="upper" :class="minimum ? 'disable' : ''">
          <van-icon :name="require('../assets/images/upper_light.png')" size="20" />
          <div>上一章</div>
        </div>
        <div class="control-item" @click="goToCatalogue">
          <van-icon :name="require('../assets/images/catalogue_light.png')" size="20" />
          <div>目录</div>
        </div>
        <div class="control-item" @click="isLight = !isLight">
          <van-icon :name="require('../assets/images/light.png')" size="20" />
          <div>夜间</div>
        </div>
        <div class="control-item" @click="lower" :class="maximum ? 'disable' : ''">
          <van-icon :name="require('../assets/images/lower_light.png')" size="20" />
          <div>下一章</div>
        </div>
      </div>
      <div class="bottom dark-control" v-else>
        <div class="control-item" @click="upper" :class="minimum ? 'disable' : ''">
          <van-icon :name="require('../assets/images/upper_dark.png')" size="20" />
          <div>上一章</div>
        </div>
        <div class="control-item" @click="goToCatalogue">
          <van-icon :name="require('../assets/images/catalogue_dark.png')" size="20" />
          <div>目录</div>
        </div>
        <div class="control-item" @click="isLight = !isLight">
          <van-icon :name="require('../assets/images/dark.png')" size="20" />
          <div>日间</div>
        </div>
        <div class="control-item" @click="lower" :class="maximum ? 'disable' : ''">
          <van-icon :name="require('../assets/images/lower_dark.png')" size="20" />
          <div>下一章</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  export default {
    name: 'Read',

    data() {
      return {
        // 当前章节索引值
        index: 0,
        // 正文数据(滚动)
        contentData: [],
        // 正文数据（翻页）
        contentDataTurn: [],
        // 标题
        title: '正在加载',
        // 点击显示控制台
        isControl: false,
        // 点击切换阅读模式
        isLight: true,
        // 阅读模式数据
        readModeData: [
          {
            key: '日间',
            upperIcon: '../assets/images/upper_light.png',
            catalogueIcon: '../assets/images/catalogue_light.png',
            keyIcon: '../assets/images/light.png',
            lowerIcon: '../assets/images/lower_light.png'
          },
          {
            key: '夜间',
            upperIcon: '../assets/images/upper_dark.png',
            catalogueIcon: '../assets/images/catalogue_dark.png',
            keyIcon: '../assets/images/dark.png',
            lowerIcon: '../assets/images/lower_dark.png'
          }
        ],
        // 目录数据
        catalogueData: [],
        // 显示目录
        showCatalogue: false,
        // 最大最小章节
        maximum: false,
        minimum: true,
        // 标题栏
        isBar: true,
        // 字体大小
        fontSize: 15,
        // 当前阅读模式
        operation: 0,
        // operation: 1,
        // 阅读模式数据
        operationData: ["滚动", "翻页"],
        // 轮播图dom元素
        swipeEl: null,
        // 记录源数据
        sourceData: []
      }
    },

    created() {
      // 获取本地存储的数据
      let oldBookShelf = localStorage.getItem('bookShelf');
      // 转换成json格式
      oldBookShelf = JSON.parse(oldBookShelf);
      if(oldBookShelf == null) {
        return;
      }
      let isLoadGame = false;
      // 遍历
      oldBookShelf.forEach((item, index) => {
        // 判断是否已经存在
        if(item.bookId === this.$route.query.bookId) {
          // 读取用户索引值
          this.index = item.index;
          // 判断左按钮状态
          if(this.index > 0) {
            this.minimum = false;
          }
          // 使用用户记录获取书籍正文
          this.getContentData(item.link);
          // 获取书籍源（目录按钮用）
          this.getBookSources();
          // 监听页面滚动
          window.addEventListener('scroll', this.scrollToTop);
          isLoadGame = true;
          return;
        }
      })
      if(!isLoadGame) {
        // 如果不存在用户浏览记录则使用传入的link获取书籍正文
        this.getContentData(this.$route.query.link);
        // 获取书籍源（目录按钮用）
        this.getBookSources();
        // 监听页面滚动
        window.addEventListener('scroll', this.scrollToTop);
      }
    },

    // 数据更新完成
    updated() {
      // 读取用户记录
      this.loadGame();
      // 读取游客记录
      // this.touristLoadGame();
    },

    watch: {
      // 监听阅读模式
      isLight() {
        // 获取本地存储的数据
        let oldBookShelf = localStorage.getItem('bookShelf');
        // 转换成json格式
        oldBookShelf = JSON.parse(oldBookShelf);
        if(oldBookShelf == null) {
          return;
        }
        // 遍历
        oldBookShelf.forEach((item, index) => {
          // 判断是否已经存在
          if(item.bookId === this.$route.query.bookId) {
            // 存在则将用户浏览当前位置记录起来
            item.isLight = this.isLight;
          }
        })
        // 转换成字符串
        oldBookShelf = JSON.stringify(oldBookShelf);
        // 存储到本地存储
        localStorage.setItem('bookShelf', oldBookShelf);
      },

      // 监听控制台
      isControl() {
        // 当控制台发生变化标题栏同步执行
        this.isBar = this.isControl;
      },

      // 监听阅读模式的切换
      operation() {
        // 存储正文数据（翻页）
        this.$nextTick(() => {
          // 获取dom元素
          this.swipeEl = this.$refs.swipe;

          if(this.$refs.swipe == undefined) return;
          // 重置数据
          this.contentDataTurn = [];

          // 获取宽高
          let width = this.swipeEl.$el.clientWidth - 16;
          let height = this.swipeEl.$el.clientHeight - 16;
          // console.log('width:',width,'height:',height);

          // 计算每行每列能显示多少个字
          // let w = Math.floor(width / (this.fontSize * 1.2));
          let w = Math.floor(width / (this.fontSize));
          // let h = Math.floor(height / (this.fontSize + 1));
          let h = Math.floor(height / (this.fontSize + 28));
          // console.log('w:',w,'h:',h);

          // 计算每页显示总字数
          let count = w * h;
          // console.log('count',count);

          // console.log(res.data.chapter.cpContent.length);
          // console.log(res.data.chapter.cpContent);
          let data = this.sourceData + '\n-----------------下一章请手动切换-----------------';

          // 计算遍历次数
          let number = Math.ceil(data.length / count);
          // console.log('number',number);

          // 设置步长
          let end = count;
          // 开始裁剪数据
          // console.log('总字数',res.data.chapter.cpContent.length);
          for(let i = 0; i < number; i++) {
            let arr = data.slice((i * count), end).split('\n');


            this.contentDataTurn.push(arr);



            // this.contentDataTurn.push(res.data.chapter.cpContent.slice((i * count), end));
            // console.log('截取',(i * count), end);
            // console.log(res.data.chapter.cpContent.slice((i * count), end));
            end += count;
          }
          // console.log(this.contentDataTurn);
        });
      },

      // 监听字体大小改变
      fontSize() {
        // 存储正文数据（翻页）
        this.$nextTick(() => {
          // 获取dom元素
          this.swipeEl = this.$refs.swipe;

          if(this.$refs.swipe == undefined) return;
          // 重置数据
          this.contentDataTurn = [];

          // 获取宽高
          let width = this.swipeEl.$el.clientWidth - 16;
          let height = this.swipeEl.$el.clientHeight - 16;
          // console.log('width:',width,'height:',height);

          // 计算每行每列能显示多少个字
          // let w = Math.floor(width / (this.fontSize * 1.2));
          let w = Math.floor(width / (this.fontSize));
          // let h = Math.floor(height / (this.fontSize + 1));
          let h = Math.floor(height / (this.fontSize + 28));
          // let h = Math.floor(height / (this.fontSize + (this.fontSize * 1.8)));
          // console.log('w:',w,'h:',h);

          // 计算每页显示总字数
          let count = w * h;
          // console.log('count',count);

          // console.log(res.data.chapter.cpContent.length);
          // console.log(res.data.chapter.cpContent);
          let data = this.sourceData + '\n-----------------下一章请手动切换-----------------';

          // 计算遍历次数
          let number = Math.ceil(data.length / count);
          // console.log('number',number);

          // 设置步长
          let end = count;
          // 开始裁剪数据
          // console.log('总字数',res.data.chapter.cpContent.length);
          for(let i = 0; i < number; i++) {
            let arr = data.slice((i * count), end).split('\n');


            this.contentDataTurn.push(arr);



            // this.contentDataTurn.push(res.data.chapter.cpContent.slice((i * count), end));
            // console.log('截取',(i * count), end);
            // console.log(res.data.chapter.cpContent.slice((i * count), end));
            end += count;
          }
          // console.log(this.contentDataTurn);
        });
      }
    },

    methods: {
      // 获取书籍正文
      getContentData(link) {
        // 重置
        window.scrollTo(0, 0);
        this.axios.get(`chapters/${link}`, {
          params: {}
        }).then(res => {
          // console.log('res', res);
            this.isControl = true;
          if(res.status === 200) {
            this.title = res.data.chapter.title;
            // 存储正文数据
            this.contentData = res.data.chapter.cpContent.split('\n');
            // 存储源数据
            this.sourceData = res.data.chapter.cpContent;

            // 存储正文数据（翻页）
            this.$nextTick(() => {
              // 获取dom元素
              this.swipeEl = this.$refs.swipe;

              if(this.$refs.swipe == undefined) return;

              // 获取宽高
              let width = this.swipeEl.$el.clientWidth - 16;
              let height = this.swipeEl.$el.clientHeight - 16;
              // console.log('width:',width,'height:',height);

              // 计算每行每列能显示多少个字
              // let w = Math.floor(width / (this.fontSize * 1.2));
              let w = Math.floor(width / (this.fontSize));
              // let h = Math.floor(height / (this.fontSize + 1));
              let h = Math.floor(height / (this.fontSize + 28));
              // console.log('w:',w,'h:',h);

              // 计算每页显示总字数
              let count = w * h;
              // console.log('count',count);

              // console.log(res.data.chapter.cpContent.length);
              // console.log(res.data.chapter.cpContent);
              res.data.chapter.cpContent += '\n-----------------下一章请手动切换-----------------';

              // 计算遍历次数
              let number = Math.ceil(res.data.chapter.cpContent.length / count);
              // console.log('number',number);

              // 设置步长
              let end = count;
              // 开始裁剪数据
              // console.log('总字数',res.data.chapter.cpContent.length);
              for(let i = 0; i < number; i++) {
                let arr = res.data.chapter.cpContent.slice((i * count), end).split('\n');


                this.contentDataTurn.push(arr);



                // this.contentDataTurn.push(res.data.chapter.cpContent.slice((i * count), end));
                // console.log('截取',(i * count), end);
                // console.log(res.data.chapter.cpContent.slice((i * count), end));
                end += count;
              }
              // console.log(this.contentDataTurn);
            });







            // console.log(this.contentData);
            // 获取本地存储的数据
            let oldBookShelf = localStorage.getItem('bookShelf');
            // 转换成json格式
            oldBookShelf = JSON.parse(oldBookShelf);
            if(oldBookShelf == null) {
              return;
            }
            // 遍历
            oldBookShelf.forEach((item, index) => {
              // 判断是否已经存在
              if(item.bookId === this.$route.query.bookId) {
                // 存储章节索引
                item.index = this.index;
                // 存储link
                item.link = link;
              }
            })
            // 转换成字符串
            oldBookShelf = JSON.stringify(oldBookShelf);
            // 存储到本地存储
            localStorage.setItem('bookShelf', oldBookShelf);
          }
        }).catch(err => {
          console.log('err', err);
        })
      },

      // 上一章
      upper() {
        if(this.index <= 0) {
          return;
        }
        this.index--;
        if(this.index <= 0) {
          this.minimum = true;
        }
        this.maximum = false;
        let link = this.catalogueData[this.index].link;
        link = encodeURIComponent(link);
        this.getContentData(link);
      },

      // 下一章
      lower() {
        if(this.index >= this.catalogueData.length) {
          return;
        }
        this.index++;
        if(this.index >= this.catalogueData.length) {
          this.maximum = true;
        }
        this.minimum = false;
        let link = this.catalogueData[this.index].link;
        link = encodeURIComponent(link);
        this.getContentData(link);
      },

      // 获取书籍源
      getBookSources() {
        this.axios.get('book-sources', {
          params: {
            view: 'summary',
            book: this.$route.query.bookId
          }
        }).then(res => {
          // console.log('res', res);
          if(res.status === 200) {
            // 第一个默认是正版书源
            this.getBookChapters(res.data[0]._id);
          }
        }).catch(err => {
          console.log('err', err);
        })
      },

      // 获取章节
      getBookChapters(_id) {
        this.axios.get(`book-chapters/${_id}`, {
          // params: {}
        }).then(res => {
          // console.log('res', res);
          if(res.status === 200) {
            this.catalogueData = res.data.chapters;
          }
        }).catch(err => {
          console.log('err', err);
        })
      },

      // 跳转到目录页
      goToCatalogue() {
        this.$router.push({name: 'Catalogue', query: {bookId: this.$route.query.bookId}});
      },

      // 返回到书籍详情页
      returnBookDetails() {
        // 移除事件监听
        window.removeEventListener("scroll", this.scrollToTop);
        // 开始阅读直接跳过其他步骤
        // 这里是书架进入
        if(this.$route.query.isRead != undefined) {
          this.$router.push({name: 'BookDetails', query: {bookId: this.$route.query.bookId, isSearch: true}});
        }else {
          this.$router.go(-1);
        }
      },

      // 监听滚动
      scrollToTop() {
        let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
        // console.log(scrollTop);
        // 获取本地存储的数据
        let oldBookShelf = localStorage.getItem('bookShelf');
        // 转换成json格式
        oldBookShelf = JSON.parse(oldBookShelf);
        if(oldBookShelf == null) {
          return;
        }
        // 遍历
        oldBookShelf.forEach((item, index) => {
          // 判断是否已经存在
          if(item.bookId === this.$route.query.bookId) {
            // 存在则将用户浏览当前位置记录起来
            item['scrollTop' + item.index] = scrollTop;
            // console.log(item['scrollTop' + item.index]);
          }
        })
        // 转换成字符串
        oldBookShelf = JSON.stringify(oldBookShelf);
        // 存储到本地存储
        localStorage.setItem('bookShelf', oldBookShelf);
      },

      // 读取用户记录
      loadGame() {
        // 获取本地存储的数据
        let oldBookShelf = localStorage.getItem('bookShelf');
        // 转换成json格式
        oldBookShelf = JSON.parse(oldBookShelf);
        if(oldBookShelf == null) {
          return;
        }
        // 遍历
        oldBookShelf.forEach((item, index) => {
          // 判断是否已经存在
          if(item.bookId === this.$route.query.bookId) {
            // console.log(item.bookId);
            // console.log(this.$route.query.bookId);
            // 设置浏览位置
            // console.log('loadGame',item['scrollTop' + item.index]);
            window.scrollTo(0, item['scrollTop' + item.index]);
            // 设置阅读模式
            this.isLight = item.isLight;
          }
        })
      },

      // 读取游客记录
      touristLoadGame() {
        // 获取本地存储的数据
        let oldBookShelf = localStorage.getItem('bookShelf');
        // 转换成json格式
        oldBookShelf = JSON.parse(oldBookShelf);
        if(oldBookShelf == null) {
          return;
        }
        // 遍历
        oldBookShelf.forEach((item, index) => {
          // 判断是否已经存在
          if(item.bookId === this.$route.query.bookId) {
            // 设置浏览位置
            // console.log('loadGame',item['scrollTop' + item.index]);
            window.scrollTo(0, item['scrollTop' + item.index]);
            // 设置阅读模式
            this.isLight = item.isLight;
          }
        })
      },

      // 切换字体大小
      toggleFontSize(key) {
        // if(this.fontSize <= 1 || this.fontSize >= 100) return;
        if(key == 'enlarge') {
          if(this.fontSize >= 100) return;
          this.fontSize++;
        }else {
          if(this.fontSize <= 1) return;
          this.fontSize--;
        }
      }
    },

    // 销毁时
    destroyed() {
      // 移除事件监听
      window.removeEventListener("scroll", this.scrollToTop);
    },
  }
</script>

<style lang="less" scoped>
// 内容区日间模式
.light-read {
  background-color: #f1e5c7 !important;
  color: #333 !important;
}
// 内容区夜间模式
.dark-read {
  background-color: #222 !important;
  color: #999 !important;
}
// 控制台日间模式
.light {
  background-color: #fff !important;
  color: #777 !important;
}
// 控制台夜间模式
.dark {
  background-color: #000 !important;
  // color: #777 !important;
}
// 导航条日间模式
::v-deep .van-nav-bar.light-read {
  background-color: #fff !important;
}
// 导航条夜间模式
::v-deep .van-nav-bar.dark-read {
  background-color: #000 !important;
}
.nav-bar {
  position: sticky;
  top: 28px;
  z-index: 999999;
}
.control {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 30px 10px;
  z-index: 999999;
  .top {
    display: flex;
    align-items: center;
    justify-content: center;
    padding-bottom: 20px;
    color: #999;
    font-size: 15px;
    .setFontSize {
      padding: 0 20px;
    }
    .showCurrent {
      width: 56px;
      box-sizing: border-box;
    }
    .operation {
      display: flex;
      align-items: center;
      margin-top: -5px;
      &>div {
        padding: 0 20px;
        opacity: .3;
      }
      .active {
        opacity: 1;
      }
    }
  }
  .bottom {
    display: flex;
    align-items: center;
    // height: 100px;
  }
  .control-item {
    flex: 1;
    text-align: center;
    font-size: 14px;
  }
}
::v-deep .van-nav-bar .van-icon {
  color: #00bb86;
}
::v-deep .van-nav-bar__title {
  color: #00bb86;
}
.content {
  padding: 16px;
  font-size: 15px;
  text-indent: 2em;
  word-wrap: break-word;
  li {
    padding: 5px 0;
    line-height: 2;
  }
}
.my-swipe {
  position: fixed;
  top: 28px;
  bottom: 0;
  width: 100%;
  // height: 100%;
  // height: 100vh;
  .swipe-item {
    padding: 16px;
    font-size: 15px;
    text-indent: 2em;
    word-wrap: break-word;
    box-sizing: border-box;
    &>div {
      padding: 5px 0;
      line-height: 2;
    }
  }
  &.isControl {
    top: 46px + 28px;
    bottom: 140px;
  }
}
</style>